package entity;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@PersistenceCapable
public class User {
	@PrimaryKey
    @Persistent
    private String nickname;
	@Persistent
    private int score;
	@Persistent
    private int count;
	@Persistent
    private int rating;
	
	private static final int DEFAULT_RATING = 1500;
	
    public User(Entity entity) {
    	//System.out.println(entity); 	
        this.nickname = entity.getKey().getName();
        
        int score = 0;
        Object objectScore = entity.getProperty("score");
        if (objectScore instanceof Long) {
        	score = (int)(long)(Long)objectScore;
        }
        else if (objectScore instanceof Integer){
        	score = (Integer)objectScore;
        }
        this.setScore(score);
        
        int count = 0;
        Object objectCount = entity.getProperty("count");
        if (objectCount instanceof Long) {
        	count = (int)(long)(Long)objectCount;
        }
        else if (objectCount instanceof Integer){
        	count = (Integer)objectCount;
        }
        this.setCount(count);
        
        int rating = 0;
        Object objectRating = entity.getProperty("rating");
        if (objectRating instanceof Long) {
        	rating = (int)(long)(Long)objectRating;
        }
        else if (objectRating instanceof Integer){
        	rating = (Integer)objectRating;
        }
        this.setRating(rating);
	}
	
	public User(String _nickname) {
		this.setNickname(_nickname);
		this.setScore(DEFAULT_RATING);
		this.setCount(1);
	}
	
	public String getNickname() {
		return nickname;
	}
	
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	
	public int getScore() {
		return score;
	}
	
	public void setScore(int score) {
		this.score = score;
	}
	
	public void modScore(int offset) {
		this.setScore(this.score + offset);
	}
	
	public int getCount() {
		return count;
	}
	
	public void setCount(int count) {
		this.count = count;
	}
	
	public void modCount(int offset) {
		this.setCount(this.count + offset);
	}	
	
	public int getRating() {
		return this.rating;
	}
	
	public void setRating(int rating) {
		this.rating = rating;
	}
	
    public void save() {
    	this.rating = this.score / this.count;
    	EntityManagerFactory emf = EMF.get();
    	if (emf == null) {
    		System.out.println("Unable to initialize the entity manager");
    		return;
    	}
        EntityManager em = emf.createEntityManager();
        try {
            em.merge(this);
        } finally {
            em.close();
        }
    }
    
    public static User get(String nickname)
    {
    	User user = null;
    	EntityManager em = EMF.get().createEntityManager();
        try {
            user = em.find(User.class, nickname);
        } finally {
            em.close();
        }
        return user;
    }

    private static void sendEmail(String email, String nickname) {
        if (email != null) { // send email only if user is logged in
            //System.out.println("Sending out email with this text:\n"+text);
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);
            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("ravishrestha01@gmail.com", "Blog Admin"));
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, nickname));
                msg.setSubject("Welcome to the Crowd-Sourced Imager!");
                msg.setText("We are glad you have joined CrImgur. Thank you for contributing. =)");
                Transport.send(msg);
            } catch (UnsupportedEncodingException e) {
                //     ...
            } catch (AddressException e) {
                //     ...
            } catch (MessagingException e) {
                // ...
            }  
        }
    }    
    
    public static void itemSaveTrigger(String user) {
    	User existingUser = User.get(user);
    	if (existingUser != null) {
    		existingUser.modCount(1);
    		existingUser.modScore(DEFAULT_RATING);
    		existingUser.save();
    	} else {
    		User newUser = new User(user);
    		UserService userService = UserServiceFactory.getUserService();
    		com.google.appengine.api.users.User googleUser = userService.getCurrentUser();
    		sendEmail(googleUser.getEmail(), googleUser.getNickname());
    		newUser.save(); 
    	}
    }
    
    public String toString() {
    	return ("nickname:"+nickname+"|score:"+score+"|count:"+count+"|rating:"+rating);
    }
}
